package com.yibo.support.context;

import com.yibo.support.exception.YBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring bean管理工具
 *
 * @author zhanglei
 */
@Component
public final class SpringContext implements ApplicationContextAware {

    private static final Logger LOGGER = LoggerFactory.getLogger(SpringContext.class);

    private static ApplicationContext applicationContext;

    private SpringContext(){}

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContext.applicationContext = applicationContext;
    }

    /**
     * 通过类型查询Bean
     *
     * @param beanType  类型class
     * @param <T>      类型
     * @return        Bean
     */
    public static <T>T  getBean(Class<T> beanType){
        try {return applicationContext.getBean(beanType);
        }catch (Exception e){
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug("spring context getBean by class type error : "+e.getMessage(),e);
            }
            throw new YBException("未注册上下文！");
        }
    }


    public static Object getBean(String beanName){
        try{
            return applicationContext.getBean(beanName);
        }catch (Exception e){
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug("spring context getBean by name error : "+e.getMessage(),e);
            }
            throw new YBException("未注册上下文！");
        }
    }

}
